#include "door_common.h"

#if defined(GKT_CONFIG_DOOR_MAGNETIC_ENABLE) \
	&& GKT_CONFIG_DOOR_MAGNETIC_ENABLE	\
	&& defined(GKT_CONFIG_DOOR_MAGNETIC_WKIO_PIN) \
	&& defined(GKT_CONFIG_DOOR_MAGNETIC_GPIO_PIN)

#if (0 == GKT_CONFIG_DOOR_MAGNETIC_DETECT_LEVEL)
#define DOOR_MAGNETIC_WKIO_POLARITY	GKT_WKIO_POL_FALL_EDGE
#define DOOR_MAGNETIC_GPIO_FLAGS	\
	(GKT_GPIO_F_INPUT | GKT_GPIO_F_PULL_UP | GKT_GPIO_F_INT_EDGE_FALL \
		| GKT_GPIO_F_INT_DEBOUNCE | GKT_GPIO_F_INT_MASKED)
#else
#define DOOR_MAGNETIC_WKIO_POLARITY	GKT_WKIO_POL_RAISE_EDGE
#define DOOR_MAGNETIC_GPIO_FLAGS	\
	(GKT_GPIO_F_INPUT | GKT_GPIO_F_PULL_DOWN | GKT_GPIO_F_INT_EDGE_RAISE \
		| GKT_GPIO_F_INT_DEBOUNCE | GKT_GPIO_F_INT_MASKED)
#endif

typedef struct _door_magnetic {
	int	detect;
	int	wakedup;
} door_magnetic_s;
static door_magnetic_s s_door_magnetic;

int gkt_door_magnetic_is_detected(void)
{
	uint32_t level;
	int retval;

	retval = gkt_gpio_get_pin_level(GKT_CONFIG_DOOR_MAGNETIC_GPIO_PIN, 
				&level);
	return ((GKT_SUCCESS == retval) 
			&& (GKT_CONFIG_DOOR_MAGNETIC_DETECT_LEVEL == level)) ? 1 : 0;
}

static void door_magnetic_intr_callback(uint32_t pin)
{
	int detect;

	gkt_unused(pin);

	detect = gkt_door_magnetic_is_detected();
	gkt_trace("door_magnetic_intr: %d --> %d\n", 
		s_door_magnetic.detect, detect);

	if (s_door_magnetic.detect != detect) {
		s_door_magnetic.detect = detect;
		door_inner_notify(GKT_DOOR_NOTIFY_MAGNETIC, detect);
	}
}

int gkt_door_magnetic_init(void)
{
	gkt_wkio_attr_s attr;
	int retval;

	retval = gkt_gpio_config(GKT_CONFIG_DOOR_MAGNETIC_GPIO_PIN,
					DOOR_MAGNETIC_GPIO_FLAGS, 
					door_magnetic_intr_callback);
	if (retval != GKT_SUCCESS) {
		gkt_error("door_magnetic: config gpio failed %d\n", retval);
		return retval;
	}
	s_door_magnetic.detect = gkt_door_magnetic_is_detected();
	gkt_gpio_interrupt_unmask(GKT_CONFIG_DOOR_MAGNETIC_GPIO_PIN);

	attr.polarity = DOOR_MAGNETIC_WKIO_POLARITY;
	attr.check = NULL;
	attr.notify = NULL;
	retval = gkt_wkio_set(GKT_CONFIG_DOOR_MAGNETIC_WKIO_PIN, &attr);
	if (retval != GKT_SUCCESS) {	
		gkt_error("door_magnetic: wkio set failed %d\n", retval);
		return retval;
	}

	s_door_magnetic.wakedup = 0;
	if ((GKT_SYSTEM_RESET_WAKEUP == g_system_info.reset_mode)
		&& s_door_magnetic.detect) 
	{
		s_door_magnetic.wakedup = gkt_wkio_is_wakeup(GKT_CONFIG_DOOR_MAGNETIC_WKIO_PIN);
		if (s_door_magnetic.wakedup)
			gkt_wakeup_set_source(GKT_WAKEUP_SRC_door_magnetic);
	}	

	return GKT_SUCCESS;
}

#endif

